<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12">
            <a-form-model-item label="业务分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryCode">
              <business-category-name-select v-model="model.categoryCode" @back="handleChangeCategoryName"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="合同占比(%)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractRate">
              <a-input-number
                :max="99999999"
                :min="0"
                :precision="2"
                v-model="model.contractRate"
                placeholder="请输入合同占比"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="合同分配额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractAmount">
              <a-input-number
                :max="99999999"
                :min="0"
                :precision="2"
                v-model="model.contractAmount"
                placeholder="请输入合同分配额"
                style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="切割合同额(元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cutContractAmount">
              <a-input-number
                :max="99999999"
                :min="0"
                :precision="2"
                v-model="model.cutContractAmount"
                placeholder="请输入切割合同额"
                style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productTeam">
              <select-team-input
                v-model="model.productTeam"
                :tdlx="2"
                :triggerChange="true"
                @back="handleChangeProductTeam"
              />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item label="生产公司" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productCompanyId">
              <select-Company-input disabled placeholder="请选择生产公司" v-model="model.productCompanyId" />

            </a-form-model-item>
          </a-col> -->
          <a-col :span="24">
            <a-form-model-item label="任务说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskDescription">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.taskDescription" rows="4" placeholder="请输入任务说明"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { getAction } from '@/api/manage'
import BusinessCategorySelect from '@views/erp/components/BusinessCategorySelect';
import BusinessCategoryNameSelect from '@views/erp/components/BusinessCategoryNameSelect'
import SelectTeamInput from '@views/scy/components/SelectTeamInput';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep';
import SelectTaskProgressInput from './SelectTaskProgressInput'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'

export default {
  name: 'ErpOmcTaskDistributionMemberForm',
  components: {
    BusinessCategoryNameSelect,
    BusinessCategorySelect,
    SelectTeamInput,
    SelectUserByDep,
    SelectTaskProgressInput,
    SelectCompanyInput
  },
  props: {
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    templateDataList: {
      type: Array,
      default: () => []
    },
    estimatedContractAmount: {
      type: [Number, String],
      default: 0
    },
    separateContractAmount: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      model: {},
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        categoryCode: [
          { required: true, message: '请选择业务分类' }
        ],
        contractRate: [
          { required: true, message: '请输入合同占比' }
        ],
        contractAmount: [
          { required: true, message: '请输入合同分配额' }
        ],
        cutContractAmount: [
          { required: true, message: '请输入切割合同额' }
        ],
        productTeam: [
          { required: true, message: '请选择生产团队' }
        ]
      },
      url: {
        add: '/api/erp/omc/project/erpOmcProjectTask/add',
        edit: '/api/erp/omc/project/erpOmcProjectTask/edit',
        queryById: '/api/erp/omc/project/erpOmcProjectTask/queryById',
        queryPayGradeByEmpId: '/api/erp/files/employee/erpEmployeeFile/queryPayGradeByEmpId'
      },
      disabledOnly: false,
      disableOld: false,
      disableNew: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    // 成员匹配合同额 和 任务委托合同额的计算，当改变后触发 watch 重新计算合同额占比
    rate() {
      return [this.model.contractAmount, this.estimatedContractAmount]
    },
    laborCost() {
      return [this.model.dayCost, this.model.expectWorkTime, this.model.projectPerformance]
    }
  },
  watch: {
    laborCost: {
      handler() {
        const { dayCost, expectWorkTime, projectPerformance } = this.model
        const format = (num) => (Number(num) || 0)

        this.model.laborCost = format(dayCost) * format(expectWorkTime) + format(projectPerformance)
      },
      immediate: true
    }
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    handleChangeCategoryName(item) {
      if (!item) {
        this.$set(this.model, 'categoryName', undefined)
      } else {
        this.$set(this.model, 'categoryName', item.categoryName)
      }
    },
    handleChangeProductTeam(event) {
      const item = event[0]
      if (!item) {
        this.$set(this.model, 'teamLeader', undefined)
        // this.$set(this.model, 'productCompanyId',val[0].belongCompanyId)
      } else {
        this.$set(this.model, 'teamLeader', item.tdfzr)
        this.$set(this.model, 'productTeam_dictText', item.aliasName)
        this.$set(this.model, 'productCompanyId',item.belongCompanyId)

      }
    },
    handleMemberChange(data) {
      const item = data[0]
      if (!item) return void (0)

      getAction(this.url.queryPayGradeByEmpId, { empId: item.empId })
        .then(response => {
          // debugger
          this.model.dayCost = response.result
        })
    },
    productTeamChange(val) {
      // debugger;
      getAction('/api/erp/omc/teammanager/erpOmcTeamManager/queryById', { id: val }).then((res) => {
        if (res.success) {
          // debugger;
          let data = res.result.records || res.result
          this.$set(this.model, 'productTeam', val)
          this.$set(this.model, 'teamLeader', data.tdfzr)
        }
      })
    },
    handleRateChange(e) {
      if (this.assignedAmount !== 0) {
        let amount = this.assignedAmount * e / 100
        this.model.contractAmount = Math.round((amount + Number.EPSILON) * 100) / 100;
      } else {
        this.model.contractAmount = 0
      }
    },
    handleAmountChange(e) {
      if (this.assignedAmount !== 0) {
        let rate = e / this.assignedAmount * 100
        this.model.contractRate = Math.round((rate + Number.EPSILON) * 100) / 100;
      } else {
        this.model.contractRate = 0
      }
    },
    businessCategoryHandle(obj) {
      if (obj) {
        this.model.categoryName = obj.categoryName
      }
    },
    add() {
      this.edit(this.modelDefault);
    },
    edit(record, flag) {
      this.$refs['form'].clearValidate();
      Object.assign(this.$data, this.$options.data())

      this.model = Object.assign({}, record);
      var keys = Object.keys(this.model);
      // 是否关联任务进度
      // if (keys.indexOf('isRelatedTaskNode') == -1 || this.model.isRelatedTaskNode == null) {
      //   this.$set(this.model, 'isRelatedTaskNode', 0)
      // }
      // 是否关联任务
      // if (keys.indexOf('isRelatedTask') == -1 || this.model.isRelatedTask == null) {
      //   this.$set(this.model, 'isRelatedTask', 1)
      // }
      if (this.model.isRelatedTaskNode == 0) {
        this.$delete(this.validatorRules, 'taskNodeId');
      } else {
        this.$set(this.validatorRules, 'taskNodeId', [{ required: true, message: '请选择关联任务进度!' }]);
      }
      if (flag == '1') {
        this.disableNew = false
        this.disableOld = true
      } else {
        this.disableOld = false
        this.disableNew = false
      }
      this.visible = true;
    },

    // 请选择是否关联任务
    relatedTaskInput (item) {
      this.$set(this.model, 'isRelatedTaskNode', 0)
      this.$set(this.model, 'taskNodeId', undefined)
      this.$set(this.model, 'taskNodeId_dictText', undefined)
    },

    // 请选择是否关联任务进度
    collectionDateInput (item) {
      this.$set(this.model, 'taskNodeId', undefined)
      this.$set(this.model, 'taskNodeId_dictText', undefined)
      if (item == 0) {
        this.$delete(this.validatorRules, 'taskNodeId');
      } else {
        this.$set(this.validatorRules, 'taskNodeId', [{ required: true, message: '请选择关联任务进度!' }]);
      }
    },

    // 选择任务进度
    onChangeTaskNodeId (item) {
      if (item && item.length && item[0].nodeName) {
        this.$set(this.model, 'taskNodeId_dictText', item[0].nodeName)
      }
    },

    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          // that.confirmLoading = true;
          if (!this.model.id) {
            this.model.id = parseInt(Math.random() * 1000000000000) + '';
          }
          // this.$set(this.model, 'paymentId', this.model.id)
          this.$emit('ok', this.model);
        }
      })
    }
  }
}
</script>
